package com.jason.digest.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class SignUtils {
    private static String secret = "e10adc3949ba59abbe56e057f20f883f";


    public static String generatorSign(Map<String, Object> map) {
        map.remove("sign");
        //排序
        Map<String, Object> stringObjectMap = MapSortUtils.sortMapByKey(map);
        //转格式
        Set<Map.Entry<String, Object>> entries = stringObjectMap.entrySet();
        //存放StringBuilder
        StringBuilder sb = new StringBuilder();
        //遍历
        for (Map.Entry<String, Object> entry : entries) {
            sb.append(entry.getKey() + ":" + entry.getValue()).append("&");
        }
        //组装secret
        sb.append("secret").append(secret);
        //生产签名
        return MessageDigestUtils.encryptDigest(sb.toString(),MessageDigestUtils.SHA512);
    }

    /**
     * 校验签名
     * @param map
     * @return
     */
    public static Boolean checkSign(Map<String,Object> map){
        String sign = (String) map.get("sign");
        map.remove("sign");
        //生产Sign
        String signGenera = generatorSign(map);
        //校验Sign
        if (signGenera.equals(sign)){
            return true;
        }
        return false;
    }


    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("appId", 1);
        map.put("name", "hello");
        String s = generatorSign(map);
        System.out.println("s = " + s);
    }
}
